package ug.co.icom.kyazze.healthticket.services;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.IntentService;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.os.AsyncTask;
import cpabe.Cpabe;

/**
 * On new device login, this IntentService fetches the PHR owner's (public,
 * master and private) keys and the cpabe encrypted file. The cpabe file is
 * decypted to a text file which exposes the medical id field The user can then
 * read data from their medical record
 * 
 * @author KYAZZE MICHAEL
 * 
 */
public class IntentFileDownloadService extends IntentService {
	private static final String TAG = "IntentFileDownloadService";
	private String filepath = "healthTicket_files";
	private long User_Phone;
	File directory;
	HttpURLConnection urlConnection;
	String pubfile = directory+"/"+User_Phone+"pub_key";
	String encfile = directory+"/"+User_Phone+".cpabe";
	String prvfile = directory+"/"+User_Phone+"prv_key";
	String decfile = directory+"/"+User_Phone+".txt";


	public IntentFileDownloadService() {
		super(TAG);
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		ContextWrapper contextWrapper = new ContextWrapper(
				getApplicationContext());
		directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
		
		ApplicationObject mApplication = (ApplicationObject)getApplicationContext();
		User_Phone = mApplication.getphone_number();
		
		downloadTask d_task = new downloadTask();
		d_task.execute();
		
		Cpabe test = new Cpabe();
		try {
			test.dec(pubfile, prvfile, encfile, decfile);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private class downloadTask extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {

			long val = User_Phone;

			pubfile = directory+"/"+User_Phone+"pub_key";
			encfile = directory+"/"+User_Phone+".cpabe";
			prvfile = directory+"/"+User_Phone+"prv_key";
			decfile = directory+"/"+User_Phone+".txt";
			int i = 0;
			String[] extensions = {".cpabe","pub_key","master_key","prv_key"};
        // while loop and array to download all files
			while(i<4){			
			
			try {
				URL url = new URL(
						"http://appitconsult.com/healthticket/keyfile/"+val+extensions[i]);
				// create the new connection
				urlConnection = (HttpURLConnection) url
						.openConnection();
				urlConnection.setRequestMethod("GET");
				urlConnection.setDoOutput(true);
				urlConnection.connect();
				// set save path
				File SDCardRoot = new File(directory + "/");
				File file = new File(SDCardRoot, val+extensions[i]);
				filesave(file);
				

			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			i++;
		}
//			File SDCardRoot = new File(directory + "/");
//			File file = new File(SDCardRoot, val+".txt");
//			try {
//				filesave(file);
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
			return null;
		}

	}

	private void filesave(File file) throws IOException {
		FileOutputStream fileOutput = new FileOutputStream(file);
		InputStream inputStream = urlConnection.getInputStream();
		
		
		// create a buffer...
		byte[] buffer = new byte[2048];
		int bufferLength = 0; // used to store a temporary size of the
		// buffer
		// now, read through the input buffer and write the contents to
		// the file
		while ((bufferLength = inputStream.read(buffer)) > 0) {
			fileOutput.write(buffer, 0, bufferLength);
		}
		// close the output stream when done
		fileOutput.close();

	}

}
